#include "system.h"
#include <plib.h>
#include "i2c.h"

void initI2C(int i2cBus, unsigned frequency){
    I2CSetFrequency(i2cBus, GetPeripheralClock(), frequency);
    I2CEnable(i2cBus, TRUE);
}

BOOL transmitByteI2C(int i2cBus, UINT8 data){
    while (!I2CTransmitterIsReady(i2cBus));

    if (I2CSendByte(i2cBus, data) == I2C_MASTER_BUS_COLLISION) {
	return FALSE;
    }

    while (!I2CTransmissionHasCompleted(i2cBus));

    if (!I2CByteWasAcknowledged(i2cBus)) {
	return FALSE;
    }
    return TRUE;
}

char readByteI2C(int i2cBus, int i2cAddress, UINT8 addr){
    I2CStart(i2cBus);

    transmitByteI2C(i2cBus, i2cAddress);
    transmitByteI2C(i2cBus, addr);

    I2CRepeatStart(i2cBus);
    while (!I2CTransmitterIsReady(i2cBus));
    transmitByteI2C(i2cBus, i2cAddress | 1);

    I2CReceiverEnable(i2cBus, TRUE);

    while (!I2CReceivedDataIsAvailable(i2cBus));

    BYTE i2cbyte = I2CGetByte(i2cBus);

    I2CReceiverEnable(i2cBus, FALSE);
    I2CStop(i2cBus);

    return i2cbyte;
}

void writeByteI2C(int i2cBus, int i2cAddress, UINT8 addr, BYTE data){
	I2CStart(i2cBus);

	transmitByteI2C(i2cBus, i2cAddress);
	transmitByteI2C(i2cBus, addr);
	transmitByteI2C(i2cBus, data);

	I2CStop(i2cBus);
}